package com.tjetc.Impl;

import com.tjetc.domain.Health;
import com.tjetc.domain.Newborn;
import com.tjetc.mapper.*;
import com.tjetc.service.IdCardService;
import com.tjetc.utils.Db;
import com.tjetc.vo.Result;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class IdCardServiceImpl implements IdCardService {
    private static  Result result;


    DateFormat sdf=new SimpleDateFormat("yyyyMMdd");//创建日期格式
    NewbornMapper newbornMapper= Db.getMapper(NewbornMapper.class);
    IdCardMapper idCardMapper= Db.getMapper(IdCardMapper.class);
    HealthMapper healthMapper= Db.getMapper(HealthMapper.class);
    VaccinationMapper vaccinationMapper=Db.getMapper(VaccinationMapper.class);

    public String shenfenzheng(int  id) throws ParseException {
        Newborn newborn=newbornMapper.selectByPrimaryKey(id);
        StringBuffer idchar=new StringBuffer();
        //邮政编码
        String postCode=newborn.getPostCode();
        //生日
        Date date = newborn.getBirthDate();
        String date1=sdf.format(date);

        int sex=(newborn.getGender().equals("男"))?1:0;
        Random random=new Random();
        int number=random.nextInt(50,499);
        int number1=number*2+sex;
        String  s="0123456789X";
        char[] chars=s.toCharArray();
        char ch=chars[number1%11];
        idchar.append(postCode);//6位邮政编码
        idchar.append(date1);//8位生日
        idchar.append(number);//3位顺序号
        idchar.append(ch);
        return idchar.toString();
    }
    @Override
    public Result setIdCardById(int id) throws ParseException {
        String  idCardById = idCardMapper.findIdCardById(id);
        List<Health> diseasesWithHealthInfo1 = healthMapper.getDiseasesWithHealthInfo1(id);
        if (diseasesWithHealthInfo1.size()!=0){
            return new Result(500,"请先处理疾病",null);
        }
        int i = vaccinationMapper.countVaccinationNotByNewbornId(id);
        if (i!=0){
            return new Result(500,"还有疫苗没有打完",null);
        }
        if(idCardById==null){//没设置过

            String idchar=shenfenzheng(id);
            idCardMapper.setIdCard(idchar,id);
            System.out.println(idchar);
            return new Result(200,"设置成功喽",idchar);
        }

        return new Result(500,"这个有了",null);
    }

    @Override
    public int deleteIdCardById(int id1) {
        int i = idCardMapper.deleteByPrimaryKey(id1);
        return i;
    }

    @Override
    public void updateIdCardById(int id) {
        try {
            String idchar=shenfenzheng(id);
            idCardMapper.updateIdCardById(idchar,id);
            System.out.println(idchar);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
